//
//  JDPayViewController.m
//  JiFengDaRen
//
//  Created by zhuchao on 16/10/19.
//  Copyright © 2016年 SH_iOS. All rights reserved.
//
#import "YLProgressBar.h"
#import "UserModel.h"
#import "JDPayViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "MyOrderViewController.h"

@interface JDPayViewController ()<UIWebViewDelegate>
@property(strong,nonatomic)UIWebView *webView;
@property(strong,nonatomic)YLProgressBar *newsProgressView;

@end

@implementation JDPayViewController

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;


}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    [self createNavigationBar];

    
}
-(void)createNavigationBar{
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *leftItem  = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    
    UIBarButtonItem *fixedButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    
    fixedButton.width = -5;
    
    self.navigationItem.leftBarButtonItems = @[fixedButton,leftItem];
    
    UIBarButtonItem *shut = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStyleDone target:self action:@selector(shutWebView)];
    [shut setTitleTextAttributes:@{NSFontAttributeName:KSystemFont(__I6Width(15))} forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItems = @[shut];
    
    
    
}
- (void)back:(UIBarButtonItem *)item{
    if (self.webView.canGoBack)
    {
        [self.webView goBack];
    }else{
        [self shutWebView];
    
    }
    
}

- (void)shutWebView{
    
    [self.navigationController popViewControllerAnimated:YES];

}


#pragma mark --- 添加邀请记录
-(void)createRightNavigationItem{
    
//    UIBarButtonItem *rigthItem = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(popToRootController)];
//    [rigthItem setTitleTextAttributes:@{NSFontAttributeName:KSystemFont(__I6Width(15))} forState:UIControlStateNormal];
//    self.navigationItem.rightBarButtonItem = rigthItem;
    
    
}
-(void)popToRootController{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
#pragma mark -- 初始化UI
-(void)configUI{
    
   
    self.view.backgroundColor = [UIColor whiteColor];
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0,0,KScreenWidth,KScreenHeight - KNAVIGATIONBARHEIGHT)];
    //设置代理
    _webView.delegate = self;
    //缩放整个scrollview
    _webView.scalesPageToFit = YES;

    //加载网页
    NSURL *url;
    if (self.type == 1) {
      url  = [NSURL URLWithString:@"https://h5pay.jd.com/jdpay/saveOrder"];
        NSString *body = [NSString stringWithFormat:@"%@",self.jdhtml];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
        [request setHTTPMethod: @"POST"];
        [request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];
        [_webView loadRequest: request];
        [self.view addSubview:_webView];
    }else{
        
//        NSDictionary * dic = [self dictionaryWithJsonString:self.qiuckPayDict[@"post_data"]];
//        NSLog(@"str ===== %@",dic);
//        NSString * bodyStr = [NSString stringWithFormat:@"user_id=%@&amount=%@&order_pk=%@&pay_order_id=%@&using_type=%@",dic[@"user_id"],dic[@"amount"],dic[@"order_pk"],dic[@"pay_order_id"],dic[@"using_type"]];
        
        url = [NSURL URLWithString:self.qiuckPayDict[@"url"]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:[self.qiuckPayDict[@"post_data"] dataUsingEncoding:NSUTF8StringEncoding]];
        [_webView loadRequest:request];
        [self.view addSubview:_webView];

        
//        NSString * bodyStr = [NSString stringWithFormat:@"%@?%@",self.qiuckPayDict[@"url"],self.qiuckPayDict[@"post_data"]];
//        NSURL * url = [NSURL URLWithString:bodyStr];
//        [[UIApplication sharedApplication] openURL:url];

    }
    
        _newsProgressView = [[YLProgressBar alloc]initWithFrame:CGRectMake(0,42, KScreenWidth, 2)];
        NSArray *tintColors = @[[UIColor colorWithHexString:@"fdeded"],KREDCOLOR];
        _newsProgressView.progressTintColors = tintColors;
        _newsProgressView.type   = YLProgressBarTypeFlat;
        _newsProgressView.hideStripes        = YES;
        _newsProgressView.hideTrack          = YES;
        _newsProgressView.behavior           = YLProgressBarBehaviorDefault;
        [self.navigationController.navigationBar addSubview: _newsProgressView];
}


#pragma mark - WebViewDelegate
//加载失败
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"%@",error.localizedDescription);
    [_newsProgressView setProgress:1 animated:YES];
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1  * NSEC_PER_SEC));
    
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        
        _newsProgressView.backgroundColor = [UIColor clearColor];
        [_newsProgressView removeFromSuperview];
        
    });
    
}

//网页加载完成
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
     NSLog(@"加载成功！");
    [_newsProgressView setProgress:1 animated:YES];
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1  * NSEC_PER_SEC));
    
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        
        _newsProgressView.backgroundColor = [UIColor clearColor];
        [_newsProgressView removeFromSuperview];
        
    });
    
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    //定义好JS要调用的方法, share就是调用的share方法名
    //分享app
    context[@"shareOrder"] = ^() {
        
        NSArray *args = [JSContext currentArguments];
        
        for (JSValue *jsVal in args) {
            NSLog(@"%@", jsVal.toString);
        }
        
        NSLog(@"-------End Log-------%@",args);
       
        dispatch_async(dispatch_get_main_queue(), ^{

        });

        
    };
    //返回
    context[@"closeActivity"] = ^() {
        
        NSArray *args = [JSContext currentArguments];
        
        for (JSValue *jsVal in args) {
            NSLog(@"%@", jsVal.toString);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
           [self.navigationController popToRootViewControllerAnimated:YES];
        });
               
    };
   
    //查看订单
    context[@"checkOrder"] = ^() {
        
        NSArray *args = [JSContext currentArguments];
        
        for (JSValue *jsVal in args) {
            NSLog(@"%@", jsVal.toString);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
            [self.navigationController pushViewController:[[MyOrderViewController alloc]init] animated:YES];
        });
        

       
    };
    
    //跳转到
    context[@"bindDevice"] = ^() {
        
        NSArray *args = [JSContext currentArguments];
        
        for (JSValue *jsVal in args) {
            NSLog(@"%@", jsVal.toString);
        }
        dispatch_async(dispatch_get_main_queue(), ^{

            
        });
       
    };



}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}

@end
